﻿using System;
using System.Collections.Generic;
using System.Text;
using Quartz;
using Quartz.Listener;

namespace ShootSearch.Core
{
    public class Task
    {
        public const string JOB_CONFIG = "Config";
        public const string JOB_NEXT = "Next";
        public const string JOB_CONTEXT_PATH = "ContextPath";
        public const string TAKS_CONFIG = "Task.config";

        protected Quartz.ISchedulerFactory schedulerFactory = new Quartz.Impl.StdSchedulerFactory();
        protected Quartz.IScheduler scheduler = null;

        public JobStatus Status { get; protected set; }
        public TaskConfig Config { get; set; }
        
        public void Start()
        {
            if (Status == JobStatus.Unstarted
                || Status == JobStatus.Stopped)
            {
                Status = JobStatus.Running;

                if (scheduler == null)
                {
                    scheduler = schedulerFactory.GetScheduler();
                    JobDetail detail = Config.GetCurrentJob();                    
                    scheduler.ScheduleJob(detail, new SimpleTrigger(detail.Name,null));
                    IJobListener joblisterner = new TaskListener(this);
                    scheduler.AddGlobalJobListener(joblisterner);
                    scheduler.Start();
                }
            }
        }




        public void Stop()
        {
            if (scheduler != null && Status == JobStatus.Running)
            {
                Status = JobStatus.Stopping;
                scheduler.Shutdown();
                Status = JobStatus.Stopped;
            }
            
        }

        #region TaskListener
        public class TaskListener : JobListenerSupport
        {
            Task task = null;
            public TaskListener(Task task)
            {
                this.task = task;
            }

            public override void JobWasExecuted(JobExecutionContext context, JobExecutionException jobException)
            {
                base.JobWasExecuted(context, jobException);
                task.Status = JobStatus.Completed;
            }


            public override string Name
            {
                get { return "Task Listener"; }
            }
        } 
        #endregion
    }
}
